# encoding:utf-8
# !xiami
import requests
import re

# 初始化参数
starUrl = 'https://www.xiami.com/artist/album-iim17edb?spm=a1z1s.6659509.6856549.3.z4lfoF'
memberAuth = 'gj2eTo5Nv29lhPCQG4A2dyMW5eTTSGKExtlW3uYp5VEjd9oBN9bxx6uSRQtB2SOSrl0mdvjDhHgb'
xiamiToken = '1890466bac39394c445340e4c4c743f9'
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
}
cookies = {
    'member_auth': memberAuth,
    '_xiamitoken':xiamiToken
}

def parseAlbumList(url):
    global starUrl

    resp = requests.get(url, headers=headers, cookies=cookies)
    nextPageRes = r'</a> <a class="p_redirect_l" href="([\S]*?)">下一页</a> <span>'
    nextUrl = re.findall(nextPageRes, resp.text, re.S | re.M)
    starUrl = 'https://www.xiami.com' + nextUrl[0] if nextUrl.__len__()>0 else ''

    res = r'<div class="albumThread_list" >[\s]*<ul>([\s\S]*?)</ul>[\s]*</div>[\s]*<!--albumThread_list end-->'
    albumBlock = re.findall(res, resp.text, re.S | re.M)
    albumListHtml = albumBlock[0]

    albumRes = r'<p class="cover"><a class="CDcover100" href="([\S]*?)" title="([\S]*?)">[\s]*<img src="//pic.xiami.net/images/album[\s\S]{0,1000}类别：[\s]{0,10}([\s\S]*?)[\s]*</p>'
    albumDict = dict()
    gg = re.findall(albumRes, albumListHtml, re.S | re.M)

    for i, val in enumerate(gg):
        if  '单曲' in  val[2] or '录音室专辑' == val[2]:
            albumDict[val[1]] = val[0]
    return albumDict

def parseMusicIds(albumUrl):
    resp = requests.get(albumUrl, cookies=cookies, headers=headers)

    musicListStrRes = r'<table cellspacing="0" cellpadding="0" id="track_list" class="track_list">[\s]*<tbody>[\s]*([\s\S]*?)[\s]*</tbody>[\s]*</table>[\s]*</div>[\s]*<div class="chapter_ctrl cd_count">'
    musicListStr = re.findall(musicListStrRes, resp.text, re.S | re.M)
    musicListStr = musicListStr[0] if musicListStr.__len__()>0 else print(resp.text)

    musicIdRes = r'<a class="song_toclt" href="javascript:void\(0\)" title="添加到歌单" onclick="collect\(\'([\S]*?)\'\);"><span>添加到歌单</span></a>'
    musicIdList = re.findall(musicIdRes, musicListStr, re.S | re.M)

    return musicIdList

def collectsMusic(mids,cid):
    headers['Referer'] = 'https://www.xiami.com/album/g8rX6f810?spm=0.0.0.0.0u2Djz'
    data = {'_xiamitoken': '1890466bac39394c445340e4c4c743f9', 'ids': ','.join(mids), 'list_id': cid,
            'submit': '确+定'}

    resp = requests.post(url='https://www.xiami.com/song/collects', data=data, headers=headers, cookies=cookies)
    res = r'<div class="alert alert_ok"> <strong>([\u4e00-\u9fa5]*?)</strong>'
    str = re.findall(res, resp.text, re.S | re.M)[0]
    if str == '添加成功':
        return True
    else:
        return False

def collectsAllALbum():

    while (starUrl != ''):
        albumDisc = parseAlbumList(starUrl)
        for k, v in albumDisc.items():
            success = collectsMusic(parseMusicIds('https://www.xiami.com' + v), '402408751')
            if success:
                print('收藏成功：' + k)

    print('全部完成')


collectsAllALbum()
# print(parseAlbumList(starUrl))
# # print(','.join(parseMusicIds('https://www.xiami.com/album/nmTPQO63b66')))
#
# for k, v in parseAlbumList(starUrl).items():
#     print(k)
